 
layui.define(['table','form','treeTable'], function(exports){
    var $ = layui.$
    ,form = layui.form
    ,table = layui.table
    ,setter = layui.setter
    ,admin = layui.admin
    ,treeTable = layui.treeTable;
      
    var renderTable;
    var field = '';
    var colsArr ;
    
    var currentMenuId = "5e68cc3e00ae426da7a7e8fcd07b1389";
    
    admin.req({
        url: setter.host+'/adminmanager/menu/menuListHead'
        ,type:'post'
        ,contentType: "application/json; charset=utf-8"
        ,data:'{menuId:"'+currentMenuId+'"}'
        ,done: function(res){
          //请求成功后
          if(res.status == setter.response.statusCode.status_Success){
            field = res.data;
            
            tableRender(res.data.field);
          }else{
        	  window.location.href = setter.host+'/error/toNoPower?msg='+res.msg;
          }
        }
    });
      
      
    function tableRender(header){
        colsArr = [
            {type: 'radio'},
            {field: 'menuId', title: 'ID',hide:(header.search("menuId") == -1)},
            {field: 'name', title: '名称',width:400,hide:(header.search("name") == -1)},
            {field: 'type', title: '资源类别', align:'center',templet: '#typeTpl',hide:(header.search("type") == -1)},
            {field: 'state', title: '层级', align:'center',hide:(header.search("state") == -1)},
            {field: 'icon', title: '图标',hide:true},
            {field: 'url', title: '资源地址',hide:(header.search("url") == -1)},
            {field: 'canshu', title: '替换参数',align:'center',hide:(header.search("canshu") == -1)},
            {field: 'hasField', title: '访问字段',align:'center',hide:(header.search("hasField") == -1)},
            {field: 'place', title: '显示顺序',align:'center',hide:(header.search("place")== -1)},
            {field: 'pId', title: '上级菜单',align:'center', hide:true},
            {field: 'createAuthor', title: '创建人',align:'center',hide:(header.search("createAuthor") == -1)},
            {field: 'createTime', title: '创建时间', align:'center',hide:(header.search("createTime") == -1)},
            {field: 'status', title: '状态', align:'center',style:'color:green',templet: '#statusTpl',hide:(header.search("status") == -1)}
        ];
       
        layui.each(colsArr,function(inx,val){
            field += val.hasOwnProperty('field')?val.field:'-';
            field += ',';
        })
        field = field.substring(field.indexOf(',')+1,field.length-1);
        loadTable(colsArr,field);
    }
    function loadTable(colsArr,field){
        var treeTableWhere = {};
        treeTableWhere.headField = field;
          
        renderTable = treeTable.render({
            elem: '#LAY-menu-list',
            tree: {
            iconIndex: 2,  // 折叠图标显示在第几列
            idName: 'menuId'  // 自定义id字段的名称
            ,arrowType: 'arrow1' //箭头类型
            },
            cols: colsArr,
            height: 'full-15',
            method:'post',
            contentType:"application/json; charset=utf-8",
            where:treeTableWhere,
            url: setter.host+'/adminmanager/menu/menuListBody'  
        });
    }
  
    $('.layui-btn').on('click', function(){
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });
  
    var active = {
        batchdel: function(){
            var checkData = renderTable.checkStatus()
                if(checkData.length === 0){
                    return layer.msg('请选择数据');
                }
            layer.prompt({
                formType: 1
                ,title: '敏感操作，请验证当前用户口令'
            }, function(value, index_prompt){
                var command = layui.sessionData('layuiSession').command;
                if(value == command){
                    layer.close(index_prompt);
                    layer.confirm('确定删除吗？', function(index_confirm) {
                        layer.close(index_confirm);
                        //因为是单选项，只能选择一个
                        if(checkData[0].hasOwnProperty('children')){
                            layer.confirm('该选择的删除数据有子菜单,确定都删除吗?', {icon: 3, title:'提示'}, function(index_del){
                                layer.close(index_del);
                                del(checkData[0].menuId,checkData[0].pId);
                            });
                        }else{
                            del(checkData[0].menuId,checkData[0].pId);
                        }
                    });
                }else{
                    layer.msg('口令错误');
                }  
            }); 
        }
        ,add: function(){
            layer.open({
                type: 2
                ,title: '添加菜单'
                ,content: setter.host+'/adminmanager/menu/toInsert'
                ,area: ['720px', '590px']
                ,btn: ['确定', '取消']
                ,yes: function(index, layero){
                    var iframeWindow = window['layui-layer-iframe'+ index]
                    ,submitID = 'LAY-menu-add-submit'
                    ,submit = layero.find('iframe').contents().find('#'+ submitID);
                    //监听提交
                    iframeWindow.layui.form.on('submit('+ submitID +')', function(data){
                        var indexLoad = layer.msg('添加菜单，请稍后', {
                            icon: 16
                            ,shade: 0.01
                        });
                        admin.req({
                        url: setter.host+'/adminmanager/menu/insert'
                        ,type:'post'
                        ,dataType:'json'
                        ,contentType: "application/json; charset=utf-8"
                        ,data:JSON.stringify(data.field) 
                        ,done: function(res){
                            //请求成功后
                            if(res.status == setter.response.statusCode.status_Success){
                                if(data.field.menuId == '-1'){
                                    loadTable(colsArr,field);
                                    }else{
                                        renderTable.refresh(data.field.menuId);
                                }
                            }
                            layer.close(index);
                            layer.close(indexLoad);
                            layer.msg(res.msg);
                        }
                        });
                    });  
                    submit.trigger('click');
                }
            }); 
        }
        ,edit: function(){
            var checkData = renderTable.checkStatus();
            if(checkData.length > 1){
                return layer.msg('只能选中编辑一行');
            }
            if(checkData.length ===0 ){
                return layer.msg('请选择一行数据进行编辑');
            }
            layer.open({
                type: 2
                ,title: '编辑菜单'
                ,content: setter.host+'/adminmanager/menu/toEdit'
                ,area: ['720px', '590px']
                ,btn: ['确定', '取消']
                ,success:function(editFrame,index){
                    var iframeWindow = window['layui-layer-iframe'+ index]
                    ,subBody = editFrame.find('iframe').contents();
                    //subBody.find('select[name=type]').find("option[value='button']").attr("selected",true);
                    var type = checkData[0].type;
                    if(type=='目录'){
                        type='catalog';
                        subBody.find('#menuName1').css('display','block');
                        subBody.find('#menuName2').css('display','none');
                        subBody.find('input[name=name]').val(checkData[0].name);
                    }else if(type=='菜单'){
                        type='menu';
                        subBody.find('#menuName1').css('display','block');
                        subBody.find('#menuName2').css('display','none');
                        subBody.find('input[name=name]').val(checkData[0].name);
                        
                    }else if(type=='按钮'){
                        type='button';
                        subBody.find('#menuName1').css('display','none');
                        subBody.find('#menuName2').css('display','block');
                        subBody.find('input[name=name]').val(checkData[0].name);
                        subBody.find('select[name=name1]').val(checkData[0].name);
                    }else if(type=='链接'){
                        type='link';
                        subBody.find('#menuName1').css('display','block');
                        subBody.find('#menuName2').css('display','none');
                        subBody.find('input[name=name]').val(checkData[0].name);
                        subBody.find('select[name=name1]').val(checkData[0].name);
                        type='link'
                    }else if(type=='弹窗'){
                        type='window';
                        subBody.find('#menuName1').css('display','block');
                        subBody.find('#menuName2').css('display','none');
                        subBody.find('input[name=name]').val(checkData[0].name);
                    }else if(type=='新窗'){
                        type='newWindow';
                        subBody.find('#menuName1').css('display','block');
                        subBody.find('#menuName2').css('display','none');
                        subBody.find('input[name=name]').val(checkData[0].name);
                    }
                    subBody.find('input[name=menuId]').val(checkData[0].menuId);
                    subBody.find('input[name=icon]').val(checkData[0].icon);
                    subBody.find('input[name=pId]').val(checkData[0].pId);
                    subBody.find('select[name=type]').val(type);
                    subBody.find('input[name=url]').val(checkData[0].url);
                    subBody.find('input[name=canshu]').val(checkData[0].canshu);
                    var place = checkData[0].place;
                        
                    subBody.find('input[name=place]').val(place);
                    if(checkData[0].hasField=='有'){
                        subBody.find('input[name=set]').attr('checked','checked');
                        subBody.find('input[name=set]').val('on');
                    }else if(checkData[0].hasField =='无'){
                        subBody.find('input[name=set]').removeAttr('checked');
                        subBody.find('input[name=set]').val('off');
                    }
                        
                    if(checkData[0].status=='启用')
                        subBody.find('input[name=status]').attr('checked','checked');
                    else
                        subBody.find('input[name=status]');
                }
                ,yes: function(index, layero){
                    var iframeWindow = window['layui-layer-iframe'+ index]
                    ,submitID = 'LAY-menu-edit-submit'
                    ,submit = layero.find('iframe').contents().find('#'+ submitID);
                    //监听提交
                    iframeWindow.layui.form.on('submit('+ submitID +')', function(data){
//                        data.field.menuId = checkData[0].menuId;
//                        data.field.pId = checkData[0].pId;
                        admin.req({
                            url: setter.host+'/adminmanager/menu/edit'
                            ,type:'post'
                            ,dataType:'json'
                            ,contentType: "application/json; charset=utf-8"
                            ,data:JSON.stringify(data.field)  
                            ,done: function(res){
                            //请求成功后
                            if(res.status == setter.response.statusCode.status_Success){
                                if(data.field.pId == '-1'||data.field.toChangePid=='-1'){
                                    loadTable(colsArr,field);
                                }else{
                                    renderTable.refresh(data.field.pId);
                                    //如果更新的菜单与当前修改的父菜单不一样，那么还需要刷新新修改后的菜单
                                    if(data.field.toChangePid !='' && data.field.pId != data.field.toChangePid){
                                    	renderTable.refresh(data.field.toChangePid);
                                    }
                                }
                            }
                            layer.close(index);
                            layer.msg(res.msg);
                            }
                        });
                    });  
                    submit.trigger('click');
                }
            });
        }
    }
    function del(menuId,pId){
        var indexLoad = layer.msg('删除菜单，请稍后', {
            icon: 16
            ,shade: 0.01
        });
        admin.req({
            url: setter.host+'/adminmanager/menu/batchdelMenu'
            ,type:'post'
            ,contentType: "application/json; charset=utf-8"
            ,data:'{"menuId":"'+menuId+'","pId":"'+pId+'"}'
            ,done: function(res){
                //请求成功后
                if(res.status == setter.response.statusCode.status_Success){
                        if(pId == '-1'){
                            loadTable(colsArr,field);
                        }else{
                            renderTable.refresh(pId);
                        }
                }
                layer.close(indexLoad);
                layer.msg(res.msg);
            }
        });
    }
    //对外暴露的接口
      exports('select', {});
  });